package com.whty.cms.filewps.util;


import java.nio.charset.StandardCharsets;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * @ClassName:  HmacSHA256Utils   
 * @Description:HmacSHA256 工具类
 * @author: api-gateway
 * @Copyright: 2019
 */
public class HmacSHA256Utils {

    private static final String ALGORITHM = "HmacSHA256";

    private static Base64 base64 = new Base64();
    
    /**
     * @author: api-gateway 
     * @Description: 生成密钥
     * @return
     */
	public static String generateSecretKey() {
        try {
            SecretKey secretKey = KeyGenerator.getInstance(ALGORITHM).generateKey();
            return base64.encodeToString(secretKey.getEncoded());
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    /**
     * @author: api-gateway 
     * @Description: 生成消息摘要
     * @param secretKey app密钥
     * @param content 
     * @return
     * @date:2019年8月21日 上午9:22:42
     */
    public static String digest(String secretKey, String content) {
        try {
            // 还原密钥
            byte[] secretBytes = base64.decode(secretKey);
            SecretKey secret = new SecretKeySpec(secretBytes, ALGORITHM);

            // 为mac实例初始化密钥
            Mac mac = Mac.getInstance(ALGORITHM);
            mac.init(secret);

            // 内容加密
            byte[] dataBytes = content.getBytes(StandardCharsets.UTF_8);
            return base64.encodeToString(mac.doFinal(dataBytes));
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}
